<template>
  <van-address-list
   v-model="checkedAddress"
    :list="adressList"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    :add-button-text="route.query.isCart==='1'||route.query.goodsId?'生成订单':'新增地址'"
    @select="selected"
  />
</template>

<script setup>
import { onMounted, ref } from "vue";
import { getAddressList } from "@/api/address.js";
import {useRouter,useRoute} from 'vue-router'
import { AddressList } from "vant";
  const chosenAddressId = ref(null);
let route =useRoute()
let router=useRouter()
let checkedAddress = ref(null)
// 地址列表
let adressList = ref([]);
// 进入页面 获取数据
onMounted(async () => {

  // 获取地址列表
  let arr = (await getAddressList({ limit: 100, page: 1 })).data.list || [];
 console.log(arr);
//   把 后端 数据 构造为组件 接受的数据
  adressList.value = arr.map((item) => {
    return {
        id:item.id,
        name:item.name,
        tel:item.phone,
        address:item.city+item.town,
        isDefault:item.is_default===1
    };
  });
  //先找出默认地址
// console.log(adressList.value);
  let defaultAddress =adressList.value.find(item=>item.isDefault===true)
  checkedAddress.value = defaultAddress&&defaultAddress.id||null
//   console.log(defaultAddress.id);
});

// 点击新增 跳转至新增

let onAdd=()=>{
    if(route.query.isCart){
           router.push(`create-order?checkedGoods=${route.query.checkedGoods}&addressId=${checkedAddress.value}`)
    }else if(route.query.goodsId){
                 router.push(`create-order?addressId=${checkedAddress.value}&goodsId=${route.query.goodsId}`)
    }
    else{
            router.push('/edit-address')
    } 
}
let onEdit= async(item)=>{
    router.push(`/edit-address?id=${item.id}`)
}
let selected=()=>{
    console.log('改变地址了');
}
</script>